package com.gaogzhen.designPattern.guardedSuspension;

/**
 * 消息传递类
 */
public class GuardedDecouple {
    // 房间编号
    private String identifier;
    // 具体内容
    private Object response;

    public GuardedDecouple(String identifier) {
        this.identifier = identifier;
    }

    public String getIdentifier() {
        return identifier;
    }

    /**
     * 获取响应结果
     * @return  Object 响应结果
     */
    public synchronized Object get(long timeout) {
        long begin = System.currentTimeMillis();
        long passTime = 0;
        while (response == null) {
            // 当前要等待的时间
            long waitTime = timeout - passTime;
            // 判断如果当前等待时间小于等于0，说明等待超时
            if (waitTime <= 0) {
                break;
            }
            // 如果响应结果为空，当前线程等待
            try {
                this.wait(waitTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            passTime = System.currentTimeMillis() - begin;
        }
        return response;
    }

    /**
     * 设置响应结果
     * @param o
     */
    public synchronized void setResponse(Object o) {
        if (o != null) {
            // 参数不为空，给响应结果赋值，同时唤醒等待（wait）等待的线程
            response = o;
            this.notifyAll();
        }
    }
}
